//
//  InitController.m
//  MClient
//
//  Created by Zhouyi on 10-9-26.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "InitController.h"
#import "MClientAppDelegate.h"
#import "MCFunction.h"
#import "LoginController.h"
#import "MServerStreamDAO.h"

@interface InitController(Private)

@end

@implementation InitController

- (int)identiferId {
	return 0;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	
	serverUrl = self.userDefaults.current_ServerUrl;
	partyId = self.userDefaults.current_PartyId;
	isHidePartyId = self.userDefaults.isHidePartyId;
	isSavePassword = self.userDefaults.isSavePassword;
	isGridMenu = self.userDefaults.isGridMenu;
	serverUrlField = nil;
	partyIdField = nil;
	nPickerSelRow = self.userDefaults.skin_index;
	
	[self rightBarButton:@"确定" withStyle:UIBarButtonItemStyleDone selector:@selector(selectOk:)];
	self.navigationItem.hidesBackButton = YES;

	self.title = @"初始化设置";
	self.tableview.backgroundColor = [UIColor clearColor];
	
	pickerNames = [[NSMutableArray alloc] init];
	for (int i = 0; i < self.userDefaults.skin_number; i++) {
		[pickerNames addObject:[self.userDefaults skinName:i]];
	}
	if (nPickerSelRow >= [pickerNames count]) {
		nPickerSelRow = 0;
	}
	
	picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.height-nPickerHeight, self.width, nPickerHeight)];
	picker.showsSelectionIndicator = YES;
	picker.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleWidth;
	picker.hidden = YES;
	[self.clientView addSubview:picker];
	picker.dataSource = self;
	picker.delegate = self;
	
	streamDao = [[MServerStreamDAO alloc] init];
	
	NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
    if(settingsBundle) {
        NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
		NSArray* preferenceArray = [settings objectForKey:@"PreferenceSpecifiers"];
		needServerEditor = NO;
		for (NSDictionary* item in preferenceArray) {
			if ([[item objectForKey:@"Key"] isEqualToString:@"current_ServerUrl"]) {
				needServerEditor = YES;
				break;
			}
		}
    } else {
		needServerEditor = YES;
	}
}


- (void)dealloc {
	[pickerNames release];
	[picker release];
	[streamDao release];
    [super dealloc];
}

#pragma mark ---- UITableView方法 ----
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	if (needServerEditor) {// 网络设置，登录设置，显示设置
		return 3;
	} else {
		return 2;
	}
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	if (needServerEditor) {// 网络设置，登录设置，显示设置
		if (section == 0) {
			return @"网络设置";
		} else if (section == 1) {
			return @"登录设置";
		} else {
			return @"显示设置";
		}
	} else {
		if (section == 0) {
			return @"登录设置";
		} else {
			return @"显示设置";
		}
	}
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	if (needServerEditor) {// 网络设置，登录设置，显示设置
		if (section == 0) {
			return 1;
		} else if (section == 1) {
			return self.userDefaults.needHidePartyId ? 2 : 3;
		} else {
			return [pickerNames count] > 1 ? 2 : 1;
		}
	} else {
		if (section == 0) {
			return self.userDefaults.needHidePartyId ? 2 : 3;
		} else {
			return [pickerNames count] > 1 ? 2 : 1;
		}
	}
}


- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSString *cellIdentifier = [NSString stringWithFormat:@"%d-setting-cell",indexPath.row];
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	
	int section = indexPath.section;
	if (!needServerEditor) {
		section += 1;
	}
	int row = indexPath.row;
	if ([pickerNames count] <= 1) {
		row += section==2 ? 1 : 0;
	}
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
		cell.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.accessoryType = UITableViewCellAccessoryNone;
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 90, 25)];
		label.textAlignment = UITextAlignmentLeft;
		label.tag = -1;
		label.font = [UIFont boldSystemFontOfSize:14];
		label.textColor = [UIColor blackColor];
		label.backgroundColor = [UIColor clearColor];
		[cell.contentView addSubview:label];
		[label release];
		
		switch (section*10+row) {
			case 0: 
			{
				label.text = @"服务器地址";
				UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(100, 10, 170, 25)];
				field.clearsOnBeginEditing = NO;
				[field setDelegate:self];
				field.keyboardType = UIKeyboardTypeURL;
				field.returnKeyType = UIReturnKeyDone;
				field.textAlignment = UITextAlignmentRight;
				field.tag = 0;
				field.text = serverUrl;
				field.textColor = [UIColor colorWithRed:0.282 green:0.341 blue:0.455 alpha:1];
				[field addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
				[cell.contentView addSubview:field];
				[field release];
			}
				break;
			case 10:
			{
				label.text = @"会员名";
				UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(100, 10, 170, 25)];
				field.clearsOnBeginEditing = NO;
				[field setDelegate:self];
				field.keyboardType = UIKeyboardTypeURL;
				field.returnKeyType = UIReturnKeyDone;
				field.textAlignment = UITextAlignmentRight;
				field.tag = 10;
				field.placeholder = @"输入会员名";
				field.text = self.userDefaults.current_PartyId;
				field.textColor = [UIColor colorWithRed:0.282 green:0.341 blue:0.455 alpha:1];
				[field addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
				[cell.contentView addSubview:field];
				[field release];
			}
				break;
			case 11:
			{
				label.text = @"保存密码";
				UISwitch *field = [[UISwitch alloc] initWithFrame:CGRectMake(190, 10, 200, 25)];
				[field addTarget:self action:@selector(switchValue:) forControlEvents:UIControlEventValueChanged];
				field.on = isSavePassword?YES:NO;
				[cell.contentView addSubview:field];
				field.tag = 11;
				[field release];
			}
				break;
			case 12:
			{
				label.text = @"隐藏会员名";
				UISwitch *field = [[UISwitch alloc] initWithFrame:CGRectMake(190, 10, 200, 25)];
				[field addTarget:self action:@selector(switchValue:) forControlEvents:UIControlEventValueChanged];
				field.on = isHidePartyId?YES:NO;
				[cell.contentView addSubview:field];
				field.tag = 12;
				[field release];
			}
				break;
			case 20:
			{
				label.text = @"皮肤设置";
				UILabel *lbValue = [[UILabel alloc] initWithFrame:CGRectMake(190, 10, 200, 25)];
				lbValue.textColor = [UIColor colorWithRed:0.282 green:0.341 blue:0.455 alpha:1];
				lbValue.backgroundColor = [UIColor clearColor];
				[cell.contentView addSubview:lbValue];
				lbValue.tag = 20;
				[lbValue release];
				cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			}
			break;
			case 21:
			{
				label.text = @"九宫格菜单";
				UISwitch *field = [[UISwitch alloc] initWithFrame:CGRectMake(190, 10, 200, 25)];
				[field addTarget:self action:@selector(switchValue:) forControlEvents:UIControlEventValueChanged];
				field.on = isGridMenu?YES:NO;
				[cell.contentView addSubview:field];
				field.tag = 21;
				[field release];
			}
			break;
		}
	}
	if (section*10+row == 20) {
		UILabel* lbValue = (UILabel *)[cell.contentView viewWithTag:20]; 
		lbValue.text = [pickerNames objectAtIndex:nPickerSelRow];
	}
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	int section = indexPath.section;
	if (!needServerEditor) {
		section += 1;
	}
	int row = indexPath.row;
	if ([pickerNames count] <= 1) {
		row += section==2 ? 1 : 0;
	}
	if (section*10+row == 20 && picker.hidden) {
		[picker selectRow:nPickerSelRow inComponent:0 animated:NO];
		CGRect rc = CGRectMake(0, self.height, self.width, nPickerHeight);
		picker.frame = rc;
		picker.hidden = NO;
		rc.origin.y -= rc.size.height;
		
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.3];
		picker.frame = rc;
		[UIView commitAnimations];
	} else {
		[self pickerView:nil didSelectRow:nPickerSelRow inComponent:0];
	}
}

#pragma mark ---- 键盘事件处理方法 ----

- (IBAction) textFieldDone:(id)sender
{
	[sender resignFirstResponder];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
	switch (textField.tag) {
		case 0:
			serverUrlField = textField;
			break;
		case 10:
			partyIdField = textField;
			break;

		default:
			break;
	}
}

- (void)switchValue:(UIControl *)sender {
	UISwitch *field = (UISwitch *)sender;
	
	switch (sender.tag) {
		case 11:
			isSavePassword = field.on;
			break;
		case 12:
			isHidePartyId = field.on;
			break;
		case 21:
			isGridMenu = field.on;
			break;
			
		default:
			break;
	}
}
#pragma mark ---- 按钮事件处理方法 ----
- (void) selectOk: (id) sender {
	if (serverUrlField != nil) {
		serverUrl = serverUrlField.text;
	}
	if (partyIdField != nil) {
		partyId = partyIdField.text;
	}
	self.userDefaults.isHidePartyId = isHidePartyId;
	self.userDefaults.isSavePassword = isSavePassword;
	self.userDefaults.isGridMenu = isGridMenu;
	self.userDefaults.current_ServerUrl = serverUrl;
	self.userDefaults.current_PartyId = partyId;
	if (nPickerSelRow >= 0) {
		self.userDefaults.skin_index = nPickerSelRow;
	}
	self.navigationItem.leftBarButtonItem.enabled = NO;
	
	NSString *saveLocation = [[MCFunction documentPath] stringByAppendingPathComponent:@"skins.dat"];
	NSFileManager *fileManager = [NSFileManager defaultManager];
	[fileManager removeItemAtPath:saveLocation error:nil];
	
	[fileManager createFileAtPath:saveLocation contents:nil attributes:nil];
	NSString *imageUrl = [NSString stringWithFormat:@"%@/common/mobile/iphone/%@/%@", serverUrl, partyId, @"skins.zip"];
	[streamDao downloadFileWithUrlAsync:imageUrl saveLocation:saveLocation delegate:self];
}

- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	// 解压锁文件到指定目录下
	[MCFunction unzipFile:@"skins.dat" withPath:@"skins"];
	self.userDefaults.bundlePath = [[NSBundle mainBundle] bundlePath];
	self.userDefaults.isSetupFirst = NO;
	
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)getServerError: (NSString *)returnCode returnMessage:(NSString *)returnMessage
{
	//[super getServerError:returnCode returnMessage:returnMessage];
	self.navigationItem.leftBarButtonItem.enabled = YES;
	[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark ----picker-----
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return [pickerNames count];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
	CGRect rc = CGRectMake(14, 0, self.width-28, 50);
	
	UIView *retView = [[UIView alloc] initWithFrame:rc];
	retView.backgroundColor = [UIColor colorWithPatternImage:[self.userDefaults bgViewImage:row]];
	UILabel *lable = [[UILabel alloc] initWithFrame:rc];
	lable.backgroundColor = [UIColor clearColor];
	lable.text = [pickerNames objectAtIndex:row];
	
	lable.textAlignment = UITextAlignmentCenter;
	[retView addSubview:lable];
	[lable release];
	
	return retView;
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	nPickerSelRow = row;
	CGRect rc = picker.frame;
	CGRect finalFrame = CGRectMake(rc.origin.x, 
								   self.height, 
								   rc.size.width, 
								   rc.size.height);
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(pickerHide)];
	picker.frame = finalFrame;
	[UIView commitAnimations];
}

- (void)pickerHide
{
	picker.hidden = YES;
	self.navigationController.navigationBar.tintColor = [self.userDefaults navigationBarColor:nPickerSelRow];
	self.navigationController.bgImage = [self.userDefaults bgViewImage:nPickerSelRow];
	
	[self.tableview reloadData];
}


@end
